import {Pressable, ScrollView, View} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {useTranslation} from 'react-i18next';
import {
  Button,
  Card,
  Icon,
  Search,
  Tag,
  Text,
  useAppTheme,
} from 'tsun-smart-ui';
import FastImage from 'react-native-fast-image';
import {useState} from 'react';
import {type StationDTO, stationApi} from '@/services/api/stationApi';
import PageContent, {PageTemplate} from '@/components/PageContent';
import StringUtils from '@/utils/StringUtils';
import FastImageWithSkel from '@/components/FastImageWithSkel';
const stationStatusMap = {
  normal: {
    label: 'job.status.Normal',
    color: 'success',
  },
  offline: {
    label: 'monitor.tab.title.offline',
    color: 'disabled',
  },
  pending: {
    label: 'monitor.tab.title.installing',
    color: 'warning',
  },
  installed: {
    label: 'station.installed',
    color: 'info',
  },
} as const;
const TotalMap = {
  normal: 'onlineCount',
  offline: 'offlineCount',
  pending: 'toBeInstalledCount',
  installed: 'installedCount',
} as const;
type StationStatus = keyof typeof stationStatusMap;
const defaultStationImage = require('@/assets/imgs/station-placeholder.png');
const Monitor = () => {
  const navigation = useNavigation();
  const {t} = useTranslation();
  const [activeTab, setActiveTab] = useState<StationStatus | undefined>();
  const [searchText, setSearchText] = useState('');
  const theme = useAppTheme();
  const StationItem = ({item}: {item: StationDTO}) => {
    return (
      <Card>
        <Pressable
          className=" w-full"
          onPress={() => {
            navigation.navigate('StationInfo', {
              id: item.id!,
              stationName: item.stationName,
            });
          }}>
          <View className="flex-row  flex-1 gap-x-5 ">
            <FastImageWithSkel
              source={
                item.coverImage
                  ? {uri: item.coverImage}
                  : defaultStationImage
              }
              className="  size-16 rounded-lg"
              resizeMode='cover'></FastImageWithSkel>
            <View className="flex-1">
              <View className="flex-row flex-between gap-x-2">
                <Text variant="cardTitle" className="min-w-0 flex-1">
                  {item.stationName}
                </Text>
                <Tag type={stationStatusMap[item.stationStatus!].color}>
                  {t(stationStatusMap[item.stationStatus!].label)}
                </Tag>
              </View>
              <Text
                variant="caption"
                className="mt-[5.5px]"
                style={{
                  color: theme.colors?.neutral?.primary,
                }}>
                {`${t('monitor.statType')}: ${t(item.stationType) || '--'}`}
              </Text>
              <Text
                variant="caption"
                className="mt-[2px]"
                style={{
                  color: theme.colors?.neutral?.primary,
                }}>
                {`${t('sys.app.time.zone')}: ${t(item.timezone) || '--'}`}
              </Text>
            </View>
          </View>
          <View className="flex-row items-center mt-3 gap-x-1">
            <Icon
              name="position"
              size={12}
              color={theme.colors?.neutral?.primary}></Icon>
            <Text
              className="flex-1"
              variant="caption"
              numberOfLines={1}
              style={{
                color: theme.colors?.neutral?.primary,
              }}>
              {item.address + item.detailAddress}
            </Text>
          </View>
        </Pressable>
      </Card>
    );
  };
  const filterTabs = [
    {
      id: void 0,
      title: t('monitor.chat.options.all'),
      type: undefined,
    },
    ...Object.entries(stationStatusMap).map(([key, value]) => ({
      id: value.label,
      title: t(value.label),
      type: key as StationStatus,
    })),
  ] as const;

  return (
    <View className="flex-1 px-4">
      <View className="flex-1">
        <PageContent
          renderItem={StationItem}
          api={stationApi.getUserStations}
          params={{
            stationStatus: ['normal', 'offline'].includes(activeTab!)
              ? activeTab
              : void 0,
            stationName: searchText,
            installStatus: ['pending', 'installed'].includes(activeTab!)
              ? activeTab
              : void 0,
          }}>
          <PageTemplate.default>
            {({dispatch, total, setTotal, setHasMore, restData}) => {
              return (
                <>
                  <Search
                    className="mt-[10px]"
                    placeholder={t('common.search')}
                    value={searchText}
                    onChangeText={setSearchText}
                    cancelText={t('user.logOutCancel', {defaultValue: '取消'})}
                    onSubmitEditing={() => {
                      dispatch({
                        type: 'setPageNum',
                        payload: 1,
                      });
                    }}></Search>
                  <ScrollView
                    horizontal
                    className="flex-grow-0"
                    contentContainerClassName="gap-x-6"
                    showsHorizontalScrollIndicator={false}>
                    {filterTabs.map((tab, i) => (
                      <View key={i} className=" flex-shrink-0">
                        <Button
                          size="large"
                          variant="text"
                          title={`${tab.title}${`(${
                            restData?.statusCount?.[
                              TotalMap[tab.type!] ?? 'total'
                            ] ?? '0'
                          })`}`}
                          textStyle={{
                            color:
                              activeTab === tab.type
                                ? theme.colors?.brand?.primary
                                : theme.colors?.neutral?.secondaryTitle,
                          }}
                          onPress={() => {
                            setTotal(undefined);
                            dispatch({
                              type: 'setPageNum',
                              payload: 1,
                            });
                            setHasMore(true);
                            setActiveTab(tab.type);
                          }}></Button>
                      </View>
                    ))}
                  </ScrollView>
                </>
              );
            }}
          </PageTemplate.default>
        </PageContent>
      </View>
    </View>
  );
};

export default Monitor;
